#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>
using std::cin;
using std::cout;
using std::endl;

const std::string host = "127.0.0.1";
const std::string user = "hmcjn";
const std::string passwd = "923338535";
const std::string db = "db1";
const unsigned int port = 3308;

int main()
{
    cout << mysql_get_client_info() << endl;
    MYSQL *my = mysql_init(nullptr);
    if (nullptr == my)
    {
        std::cerr << "mysql_init error" << endl;
        return 1;
    }

    if (mysql_real_connect(my, host.c_str(),
                           user.c_str(), passwd.c_str(), db.c_str(), port,
                           nullptr, 0) == nullptr)
    {
        std::cerr << "mysql_real_connect error" << endl;
        return 1;
    }
    cout << "connect MySQL success" << endl;
    mysql_set_character_set(my, "utf8mb4");

    // std::string sql = "insert into user (name, age) values('飞飞', 20);";
    std::string sql = "select * from user;";
    // std::string sql = "select * from user where id=1;";

    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        cout << sql << "success: " << n << endl;
    else
        cout << sql << "faild: " << n << endl;

    MYSQL_RES *res = mysql_store_result(my);
    if (nullptr == res)
    {
        std::cerr << "mysql_store_result error" << endl;
        return 4;
    }

    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);

    cout << "行: " << rows << endl;
    cout << "列: " << fields << endl;

    MYSQL_FIELD *feilds_array = mysql_fetch_fields(res);
    for (int i = 0; i < fields; i++)
    {
        cout << feilds_array[i].name << "\t";
    }
    cout << "\n";

    // 表内容
    for (int i = 0; i < rows; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res); // char** or char*[]
        for (int j = 0; j < fields; j++)
        {
            cout << row[j] << "\t"; // *(row+j)
        }
        cout << "\n";
    }
    // while(true)
    // {
    //     cout << "MySQL>>> ";
    //     if(!std::getline(cin, sql) || sql == "quit")
    //     {
    //         cout << "bye" << endl;
    //         break;
    //     }

    //     int n = mysql_query(my, sql.c_str());
    //     if(n == 0)
    //     {
    //         cout << sql << "success: " << n << endl;
    //     }
    //     else
    //     {
    //         cout << sql << "faild: " << n <<endl;
    //     }

    // }
    mysql_free_result(res);
    mysql_close(my);
    return 0;
}